import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '@/utils/cookie'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/oj/login',
      name: 'login',
      component: () => import('@/views/Login.vue') // 动态导入登录页
    },
    {
      path: '/',
      redirect: '/oj/login', // 默认重定向到登录页
    },
    {
      path: '/oj/layout',
      name: 'layout',
      component: () => import('@/views/Layout.vue'), // 动态导入布局页
      children: [
        {
          path: 'question',
          name: 'question',
          component: () => import('@/views/Question.vue') // 动态导入题目页
        },
        {
          path: 'exam',
          name: 'exam',
          component: () => import('@/views/Exam.vue') // 动态导入考试页
        },
        {
          path: 'updateExam',
          name: 'updateExam',
          component: () => import('@/views/UpdateExam.vue') // 动态导入更新考试页
        },
        {
          path: 'cuser',
          name: 'cuser',
          component: () => import('@/views/Cuser.vue') // 动态导入用户页
        }
      ]
    }
  ]
});


router.beforeEach((to, from, next) => {
  if (getToken()) {  // 已经登录
    if (to.path === '/oj/login') {
      next({ path: '/oj/layout/question' }); // 已登录用户不允许访问登录页
    } else {
      next(); // 允许访问其他页面
    }
  } else {
    if (to.path !== '/oj/login') {
      next({ path: '/oj/login' }); // 未登录用户强制跳转到登录页
    } else {
      next(); // 允许访问登录页
    }
  }
});

export default router


